# -*- coding: utf-8 -*-

__author__ = 'Earnest Lee'

import os
import sys
import urllib2
import xml.dom.minidom
import alfred
import commands
import subprocess

website = 'http://www.oschina.net'
""" 获取传入参数 """
query = sys.argv[1]

params = query.split('\ ', 1)

if (params[0] == 'login') :
    re = alfred.create_pwd_window("输入OSChina密码", "密码输入框")
    print re
else :
    if params[0] == 's' :
        catalog = 'software'
    elif params[0] == 'n' :
        catalog = 'news'
    elif params[0] == 'b' :
        catalog = 'blog'
    elif params[0] == 'p' :
        catalog = 'post'
    else :
        catalog = ''

keyword = params[1]
apiurl = 'http://www.oschina.net/action/api/search_list?content=' + keyword + '&catalog=' + catalog

headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}

req = urllib2.Request(apiurl, headers=headers) 
urldoc = xml.dom.minidom.parse(urllib2.urlopen( req ))

if not urldoc:
    exit()

print "<?xml version=\"1.0\"?>\n<items>"
items = urldoc.getElementsByTagName('result')

if not items:
    print alfred.Item({'uid': alfred.uid(0), 'arg': website}, u"没有找到，到开源中国官网搜搜", website)
else :
    for item in items:
        objid = item.getElementsByTagName('objid')[0].firstChild.data.replace( "&", "#" )
        url = item.getElementsByTagName('url')[0].firstChild.data
        title = item.getElementsByTagName('title')[0].firstChild.data
        print alfred.Item({'uid': alfred.uid(objid), 'arg': url}, title, url)
print "</items>\n"